package Heap;

import java.util.ArrayList;
import java.util.Arrays;

public class TestHeap {
    public int[] elem;
    public int usedSize;

    public TestHeap(){
        this.elem = new int[10];
    }

    public void createHeap(int[] array){
        for(int i =0;i < array.length;i++){
            elem[i] = array[i];
            usedSize++;
        }
        for(int p = (usedSize-1-1)/2;p>=0;p--){
            shiftDown(p,usedSize);
        }
    }

    private void shiftDown(int root,int len){
        int child = 2*root + 1;
        int parent = root;
        while(child < len){
            if(child+1 < len && elem[child] < elem[child+1]){
                child++;
            }
            if(elem[child] > elem[parent]){
                int tmp = elem[child];
                elem[child] = elem[parent];
                elem[parent] = tmp;
                parent = child;
                child = 2*parent +1;
            }else{
                break;
            }
        }
    }

    public void push(int val){
        if(isFull()){
            elem = Arrays.copyOf(elem,2*elem.length);
        }
        elem[usedSize] = val;
        shiftUp(usedSize);
        usedSize++;
    }
    private boolean isFull(){
        return usedSize == elem.length;
    }
    private void shiftUp(int child){
        int parent = (child-1)/2;
        while(child > 0){
            if(elem[child] > elem[parent]){
                int tmp = elem[child];
                elem[child] = elem[parent];
                elem[parent] = tmp;
                child = parent;
                parent = (child-1)/2;
            }else{
                break;
            }
        }
    }

    public void poll(){
        if(empty()){
            System.out.println("堆为空");
            return;
        }
        int tmp = elem[0];
        elem[0] = elem[usedSize-1];
        elem[usedSize-1] = tmp;
        usedSize--;
        shiftDown(0,usedSize);
    }
    private boolean empty(){
        return usedSize == 0;
    }

    public int peek(){
        if(empty()){
            System.out.println("堆为空");
            return -1;
        }
        return elem[0];
    }
}
